/**
 * 管理端映射配置管理js
 */	
	/**
	 * 查询映射列表信息
	 */
	function queryData(){
		dg = $('#dg').datagrid({    
		    url:local_project+'/datagrids?txcode=app015',
		    //contentType:"application/json;charset=utf-8",
			dataType:"json",
		    pagination: true,
		    rownumbers: true,
		    pagination:true,  
	        fit:true, 
	        nowrap: true, 
	        striped:true,
	        fitColumns:true,
	        striped:true,
		    pageSize:20,
		    pageList:[10,15,20,25,30,35],
		    columns:[[    
		        {field:'func_id',title:'功能跳转ID',width:'12%',align:'center'},   
		        {field:'app_id',title:'应用ID',width:'14%',align:'center'},
		        {field:'start_page',title:'跳转路由',width:'15%',align:'center'},
		        {field:'app_type',title:'应用类型',width:'7%',align:'center',formatter:  
	                function(value,row,index){  
	        		var html = "";
	        		if(row.app_type == '0'){
		        		html = "&nbsp;<text>内测</text>&nbsp;"
	        		}else{
	        			html = "&nbsp;<text>公测</text>&nbsp;"
	        		}
	        		return html;
		            }
	        	},
	        	{field:'channel',title:'渠道',width:'7%',align:'center',formatter:  
	                function(value,row,index){  
	        		var html = "";
	        		if(row.channel == '1'){
	        			html = "&nbsp;<text>手机银行</text>&nbsp;"
	        		}else if(row.channel == '2'){
	        			html = "&nbsp;<text>龙支付</text>&nbsp;"
	        		}
	        		return html;
		            }
	        	},
	        	{field:'allowplatform',title:'平台',width:'5%',align:'center',formatter:  
	                function(value,row,index){  
	        		var html = "";	        		
	        	    if(row.allowplatform == '1'){
	        			html = "&nbsp;<text>安卓</text>&nbsp;"
	        		}else if(row.allowplatform == '2'){
	        			html = "&nbsp;<text>IOS</text>&nbsp;"
	        		}else if(row.allowplatform == '0'){
	        			html = "&nbsp;<text>全部</text>&nbsp;"
	        		}
	        		return html;
		            }
	        	},
		        {field:'app_status',title:'是否生效',width:'7%',align:'center',formatter:  
	                function(value,row,index){  
	        		var html = "";
	        		if(row.app_status == '0'){
		        		html = "&nbsp;<text>失效</text>&nbsp;"
	        		}else{
	        			html = "&nbsp;<text>生效</text>&nbsp;"
	        		}
	        		return html;
		            }
	        	},
	        	{field:'time_stamp',title:'时间戳',width:'10%',align:'center'},
	        	{field:'remark_1',title:'备用1',width:'10%',align:'center'},
	        	{field:'remark_2',title:'备用2',width:'10%',align:'center'},
		        {field:'operation',title:'操作',width:'5%',align:'center',formatter:  
	                function(value,row,index){  
		        		var html = "";
		        			html += "&nbsp;<i class=\"fa fa-pencil-square-o\" style=\"color:#0767c8;font-size:16px;\" aria-hidden=\"true\"  onclick=\"showEditDetail('"+row.id+"')\"></i>";
		        			html += "&nbsp;<i class=\"fa fa-trash\" aria-hidden=\"true\" style=\"color:red;font-size:16px;\" title=\"删除\" onclick=\"del('"+row.id+"')\"></i>"; 
		        		return html;
	                }  
		       	}  
		    ]],
		    toolbar: [{
		    	text: '新增映射配置',
		        iconCls: 'fa fa-plus-circle',
		        handler: function () { 
		        	//$("#uploadFile").dialog("open");
		        	showAddDialog();
		        }
		        
		    },{
		    	text: '导入csv',
		        iconCls: 'fa fa-plus-circle',
		        handler: function () { 
		        	//$("#uploadFile").dialog("open");
		        	ImportCsv();
		        }
		    },{
		    	text: '导出csv',
		        iconCls: 'fa fa-plus-circle',
		        handler: function () { 
		        	//$("#uploadFile").dialog("open");
		        	exportDialogBtn();
		        }
		        
		    },{
		    	text: '导出全部',
		        iconCls: 'fa fa-plus-circle',
		        handler: function () { 
		        	//$("#uploadFile").dialog("open");
		        	exportExcelAll();
		        }
		        
		    },{
		    	text: '导出全量数据',
		        iconCls: 'fa fa-plus-circle',
		        handler: function () {
					exportCSVAll();
		        }

		    }],
		    //在载入远程数据产生错误的时候触发。
		    onLoadError:function(msg){
//		    	showTips(msg);
		    },
		    onLoadSuccess:function(data){  
		    } 
		}); 
		dg.datagrid({
			remoteFilter:true,
		});
		
		dg.datagrid('enableFilter');
		
		dg.datagrid('enableFilter',[{
			field: "app_type",
			type:'combobox',
			options:{
                panelHeight:'auto',
                data:[{value:'',text:''},{value:'0',text:'内测'},{value:'1',text:'公测'}],
                onChange:function(value){
                    if (value == ''){
                        dg.datagrid('removeFilterRule', 'app_type');
                    } else {
                        dg.datagrid('addFilterRule', {
                            field: 'app_type',
                            op: 'equal',
                            value: value
                        });
                    }
                    dg.datagrid('doFilter');
                }}}
		]);
		dg.datagrid('enableFilter',[{
			field: "channel",
			type:'combobox',
			options:{
                panelHeight:'auto',
                data:[{value:'',text:''},{value:'1',text:'手机银行'},{value:'2',text:'龙支付'}],
                onChange:function(value){
                    if (value == ''){
                        dg.datagrid('removeFilterRule', 'channel');
                    } else {
                        dg.datagrid('addFilterRule', {
                            field: 'channel',
                            op: 'equal',
                            value: value
                        });
                    }
                    dg.datagrid('doFilter');
                }}}
		]);
		dg.datagrid('enableFilter',[{
			field: "allowplatform",
			type:'combobox',
			options:{
                panelHeight:'auto',
                data:[{value:'',text:''},{value:'0',text:'全部'},{value:'1',text:'安卓'},{value:'2',text:'IOS'}],
                onChange:function(value){
                    if (value == ''){
                        dg.datagrid('removeFilterRule', 'allowplatform');
                    } else {
                        dg.datagrid('addFilterRule', {
                            field: 'allowplatform',
                            op: 'equal',
                            value: value
                        });
                    }
                    dg.datagrid('doFilter');
                }}}
		]);
		dg.datagrid('enableFilter',[{
			field: "app_status",
			type:'combobox',
			options:{
                panelHeight:'auto',
                data:[{value:'',text:''},{value:'0',text:'失效'},{value:'1',text:'生效'}],
                onChange:function(value){
                    if (value == ''){
                        dg.datagrid('removeFilterRule', 'app_status');
                    } else {
                        dg.datagrid('addFilterRule', {
                            field: 'app_status',
                            op: 'equal',
                            value: value
                        });
                    }
                    dg.datagrid('doFilter');
                }}}
		]);
		
		dg.datagrid('closeFilter',['operation']);
	}

//编辑窗口初始化
function details(id){
	var param = {
			"id" : id
	};
	httpRequest(param, "app016", function(msg) {
		var conf = msg.data[0];
		$("#id").val(conf.id);
		$("#edit_func_id").textbox("setValue",conf.func_id);
		$("#edit_channel").combobox("setValue",conf.channel);
		$("#edit_allowplatform").combobox("setValue",conf.allowplatform);
		$("#edit_app_id").textbox("setValue",conf.app_id);
		$("#edit_app_type").combobox("setValue",conf.app_type);
		$("#edit_start_page").textbox("setValue",conf.start_page);
		$("#edit_app_status").combobox("setValue",conf.app_status);
		$("#edit_time_stamp").val(conf.time_stamp);
		$("#edit_remark_1").textbox("setValue",conf.remark_1);
		$("#edit_remark_2").textbox("setValue",conf.remark_2);
	}, function(msg) {
		alertErrorTips("查询信息失败!");
	});
}
var token = window.top.$("meta[name='_csrf']").attr("content");
//新增映射
function addData() {
	var func_id = $("#add_func_id").val();
	var app_id = $("#add_app_id").val();
	var start_page = $("#add_start_page").val();
	
	if(func_id==""){
		alertWarnTips("功能跳转ID不能为空!");
		return;
	}
	if(app_id==""){
		alertWarnTips("应用ID不能为空!");
		return;
	}
	if(start_page==""){
		alertWarnTips("功能页路由不能为空!");
		return;
	}
	if(matchStringLength(func_id, 0, 20) == "2"){
		alertWarnTips("功能跳转ID长度不得超过20字符!");
		return ;
	};
	if(matchStringLength(app_id, 0, 64) == "2"){
		alertWarnTips("应用ID长度不得超过64字符!");
		return ;
	};
	if(matchStringLength(start_page, 0, 200) == "2"){
		alertWarnTips("功能页路由长度不得超过200字符!");
		return ;
	};
	if(matchStringLength($("#add_remark_1").val(), 0, 200) == "2"){
		alertWarnTips("备用1长度不得超过200字符!");
		return ;
	};
	if(matchStringLength($("#add_remark_2").val(), 0, 200) == "2"){
		alertWarnTips("备用1长度不得超过200字符!");
		return ;
	};
	load("信息正在导入中,请稍后...");
	$("#form1").form("submit", {
		url: local_project+"/upload?txcode=app013&_csrf="+token,
		type:"POST",
		success:function(response){
			var st = response;
			disLoad();
			if(st.indexOf("status")>=0 && JSON.parse(st).status==10){
			  	alertErrorTips("已存在相同的功能跳转ID和渠道配置！");
			  	$("#dg").datagrid("reload");
		  	}else if(st.indexOf("status")>=0 && JSON.parse(st).status==11){
		  		alertSuccessTips("添加成功！");
			  	$("#dg").datagrid("reload");
			  	$("#addDetail").window("close");
		  	}else if(st.indexOf("status")>=0 && JSON.parse(st).status==22){
		  		alertErrorTips("添加成功！但刷新缓存失败");
			  	$("#dg").datagrid("reload");
			  	$("#addDetail").window("close");
		  	}else if(st.indexOf("status")>=0 && JSON.parse(st).status==33){
		  		alertErrorTips("添加成功！但刷新通用参数表失败");
			  	$("#dg").datagrid("reload");
			  	$("#addDetail").window("close");
		  	}else{
	  			alertErrorTips("保存出错！");
	  			$("#dg").datagrid("reload");
	  		}
		  }
	}); 
	
	
}

//修改更新包
function editData() {
	var func_id = $("#edit_func_id").val();
	var app_id = $("#edit_app_id").val();
	var start_page = $("#edit_start_page").val();
	
	if(func_id==""){
		alertWarnTips("功能跳转ID不能为空!");
		return;
	}
	if(app_id==""){
		alertWarnTips("应用ID不能为空!");
		return;
	}
	if(start_page==""){
		alertWarnTips("功能页路由不能为空!");
		return;
	}
	if(matchStringLength(func_id, 0, 20) == "2"){
		alertWarnTips("功能跳转ID长度不得超过20字符!");
		return ;
	};
	if(matchStringLength(app_id, 0, 64) == "2"){
		alertWarnTips("应用ID长度不得超过64字符!");
		return ;
	};
	if(matchStringLength(start_page, 0, 200) == "2"){
		alertWarnTips("功能页路由长度不得超过200字符!");
		return ;
	};
	if(matchStringLength($("#edit_remark_1").val(), 0, 200) == "2"){
		alertWarnTips("备用1长度不得超过200字符!");
		return ;
	};
	if(matchStringLength($("#edit_remark_2").val(), 0, 200) == "2"){
		alertWarnTips("备用1长度不得超过200字符!");
		return ;
	};
	var str = '你确定要编辑映射表配置信息吗？';
	$.messager.confirm('确认', str, function(r){
		if (r){
	load("信息正在导入中,请稍后...");
	$("#form3").form("submit", {
		url: local_project+"/upload?txcode=app014&_csrf="+token,
		type:"POST",
		success:function(response){
			  	var st = response;
			  	console.log(st)
			  	disLoad();
			  	if(st.match("10")!=null){
			  		alertErrorTips("已存在相同的功能跳转ID和渠道配置！");
				  	$("#dg").datagrid("reload");
			  	}else if(st.match("11")!=null){
			  		alertSuccessTips("修改成功！");
				  	$("#dg").datagrid("reload");
				  	$("#editDetail").window("close");
			  	}else if(st.match("22")!=null){
			  		alertErrorTips("修改成功！但刷新缓存失败");
				  	$("#dg").datagrid("reload");
				  	$("#editDetail").window("close");
			  	}else if(st.match("33")!=null){
			  		alertErrorTips("修改成功！但刷新通用参数表失败");
				  	$("#dg").datagrid("reload");
				  	$("#editDetail").window("close");
			  	}else{
		  			alertErrorTips("保存出错！");
		  			$("#dg").datagrid("reload");
		  		}
		  }
	}); 
		}
	});
	
}

//根据id删除
function del(id){
	var str = '危险动作!你确定要删除该信息吗？';
	$.messager.confirm('确认', str, function(r){
		if (r){
			var str = '再次警告危险动作!你确定要删除该信息吗？';
			$.messager.confirm('确认', str, function(r){
				if (r){
					var param = {
							"id" : id
						}
					httpRequest(param, "app139", function(msg) {
					$('#dg').datagrid("reload");
					alertSuccessTips("您的操作已成功");
					}, function(msg) {
					alertErrorTips(msg);
					});
				}
			});
		}
	});
}

function exportExcelAll(){
	var param = {
			"exportWay" : "1"
		}
	httpRequest(param, "app022", function(msg) {
	alertSuccessTips("您的操作已成功");		
	downloadFileByBase64('data:text/csv;charset=utf-8,'+msg.data.ResponseEntity,msg.data.outfilename)
	}, function(msg) {
	alertErrorTips(msg);
	});

//window.location.href = local_project+"/download?txcode=app026";
}

function exportExcel(){
var param = {
	"exportWay" : "2",
		"channel" : $("#export_channel").val(),
			"allowplatform" : $("#export_allowplatform").val()
}
httpRequest(param, "app022", function(msg) {
	$("#exportDialogDetail").window("close");
alertSuccessTips("您的操作已成功");		
downloadFileByBase64('data:text/csv;charset=utf-8,'+msg.data.ResponseEntity,msg.data.outfilename)
}, function(msg) {
alertErrorTips(msg);
});
}

/**
 * 导出全量数据(CSV)
 */
function exportCSVAll(){
	var param = {}
	httpRequest(param, "app156", function(msg) {
		alertSuccessTips("您的操作已成功");
		downloadFileByBase64('data:text/csv;charset=utf-8,'+msg.data.ResponseEntity,msg.data.outfilename)
	}, function(msg) {
		alertErrorTips(msg);
	});
}

/**
 * 导入按钮
 */
function ImportCsv(){
	$("#importfile").click();
}

/**
 * 选择文件后触发上传
 */
function ImportCsv2(){
	load("信息正在导入中,请稍后...");
	var formData = new FormData();
	    formData.append("file",$('#importfile')[0].files[0]); //传给后台的file的key值是可以自己定义的
	   
	    $.ajax({
	        url: local_project + '/upload?txcode=app134', 
	        type:'POST',
	        cache: false, 
	        processData: false,
	        contentType: false,
	        data: formData,
	        success: function(data){
	        	disLoad();
	        	if(data.status==1){
	        		alertSuccessTips("导入成功！");				  	
	        	}else if(data.status==2){
	        		alertErrorTips("文件暂时只支持csv格式!");
	        	}else if(data.status==3){
	        		alertErrorTips("文件不能为空!");
	        	}else if(data.status==4){
	        		alertErrorTips("请上传合法的文件格式,后缀需要加渠道:手机银行丶龙支付,平台:全部丶安卓丶IOS,例如appconfdeploy_龙支付_IOS.csv");
	        	}else if(data.status==5){
	        		alertErrorTips("导入失败！有部分数据异常已导出csv请查看");
                    downloadFileByBase64('data:text/csv;charset=utf-8,'+data.ResponseEntity,data.outfilename)//下载错误文件csv

	        	
	        	}else if(data.status==6){
	        		alertErrorTips("csv文件请使用utf-8格式!");
	        	}else if(data.status==7){
	        		alertErrorTips("csv文件头参数不规范!");
	        	}else if(data.status==9){
	        		alertErrorTips("批量导入部分失败!");
	        	}else if(data.status==10){
	        		alertErrorTips("导入成功，但刷新缓存失败!");
	        	}else if(data.status==11){
	        		alertErrorTips("导入成功，但刷新通用参数失败!");
	        	}else{
	        		alertErrorTips("上传异常");
	        	}
	        	$("#dg").datagrid("reload");
	        },
	        error: function(err) {
	        	
	        	disLoad();
	        	alertErrorTips("上传异常");
	        }
	    })

}

function dataURLtoBlob(dataurl) {
    var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], { type: mime });
}
 
function downloadFile(url,name){
     var filename = name;
     var downloadElement = document.createElement('a');
     var href = url; //创建下载的链接
     var reg = /^["](.*)["]$/g;
     downloadElement.style.display = 'none';
     downloadElement.href = href;
     downloadElement.download = decodeURI(filename.replace(reg,"$1")); //下载后文件名
     document.body.appendChild(downloadElement);
     downloadElement.click(); //点击下载
     document.body.removeChild(downloadElement); //下载完成移除元素
     window.URL.revokeObjectURL(href); //释放掉blob对象  
}
 
function downloadFileByBase64(base64,name){
    var myBlob = dataURLtoBlob(base64)
    var myUrl = URL.createObjectURL(myBlob)
    downloadFile(myUrl,name)
}


